package com.spring.sunflower.util;

import android.graphics.Color;
import android.os.Handler;
import android.text.TextUtils;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.spring.sunflower.base.BaseApplication;
import com.spring.sunflower.common.FileUploadCallback;
import com.spring.sunflower.constant.Constant;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class AliUploadUtils {
    private Handler handler = new Handler();

    private List<OSSAsyncTask> taskList = new ArrayList();

    private static OSSClient ossClient;
    private static AliUploadUtils mInstance;

    public AliUploadUtils(String accessKeyId, String secretKeyId, String securityToken) {
        initOSClient(accessKeyId, secretKeyId, securityToken);
    }

    public AliUploadUtils() {
    }

    public static AliUploadUtils getInstance(String accessKeyId, String secretKeyId, String securityToken) {
        if (mInstance == null) {
            synchronized (AliUploadUtils.class) {
                if (mInstance == null) {
                    mInstance = new AliUploadUtils();
                }
            }
        }
        initOSClient(accessKeyId, secretKeyId, securityToken);
        return mInstance;
    }

    public static void initOSClient(String accessKeyId, String secretKeyId, String securityToken) {
        OSSStsTokenCredentialProvider provider = new OSSStsTokenCredentialProvider(accessKeyId, secretKeyId, securityToken);
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setConnectionTimeout(15000);
        clientConfiguration.setSocketTimeout(15000);
        clientConfiguration.setMaxConcurrentRequest(5);
        clientConfiguration.setMaxErrorRetry(2);
        ossClient = new OSSClient(BaseApplication.getContext(), Constant.ALI_ENDPOINT, provider, clientConfiguration);
    }

    public void upLoadFile(String uploadFilePath, FileUploadCallback callback) {
        String userID = SPUtils.getInstance().getString(Constant.KEY_USERID, "");
        if (TextUtils.isEmpty(userID)) {
            callback.onFailure("");
            ToastUtils.showShort("无法上传:(");
            return;
        }
        if (!new File(uploadFilePath).exists()) {
            callback.onFailure("");
            ToastUtils.showShort("无法上传，内容不存在:(");
            return;
        }
        String mimeType = uploadFilePath.substring(uploadFilePath.lastIndexOf("."));
        String objectKey = "app/" + userID + "/" + System.currentTimeMillis() + mimeType;
        PutObjectRequest putObjectRequest = new PutObjectRequest(Constant.ALI_BUCKET_NAME, objectKey, uploadFilePath);
        putObjectRequest.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onProgress(request, currentSize, totalSize);
                    }
                });
            }
        });
        if (ossClient == null) {
            ToastUtils.showShort("未初始化ossClient，无法上传:(");
            ToastUtils.setBgColor(Color.RED);
            ToastUtils.setMsgColor(Color.WHITE);
        } else {
            OSSAsyncTask<PutObjectResult> ossAsyncTask = ossClient.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onSuccess(request, Constant.ALI_FILE_PATH + objectKey);
                        }
                    });
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                    if (serviceException != null) {
                        String message = serviceException.getMessage();
                        String errorCode = serviceException.getErrorCode();
                        String x = " [errorCode]=" + errorCode + ",[message]=" + message;
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onFailure(x);
                            }
                        });
                    }
                    if (clientException != null) {
                        String message = clientException.getMessage();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onFailure(message);
                            }
                        });
                    }

                }
            });
            taskList.add(ossAsyncTask);
        }
    }


    public void cancelAllTask() {
        Iterator iterator = this.taskList.iterator();
        while (iterator.hasNext())
            ((OSSAsyncTask) iterator.next()).cancel();
    }

}
